package com.yape.job.Quartz;


import com.yape.dao.CrawlerTaskMapper;
import com.yape.po.CrawlerTask;
import com.yape.webCrawler.CrawlerDataService;
import com.yape.webCrawler.CrawlerService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
public class CrawlerQuartzJob implements Job {

    @Resource
    private CrawlerService crawlerService;
    @Resource
    private CrawlerTaskMapper crawlerTaskMapper;
    @Resource
    private CrawlerDataService crawlerDataService;

    @Override
    public void execute(JobExecutionContext context) {
        JobDataMap dataMap = context.getMergedJobDataMap();
        Integer taskId = dataMap.getInt("taskId");
        CrawlerTask task = crawlerTaskMapper.selectById(taskId);

        // 幂等性控制
        if (task.getRunning() != null && task.getRunning()) {
            log.warn("任务[{}]正在运行，跳过本次调度", task.getTaskName());
            return;
        }
        try {
            crawlerTaskMapper.updateRunning(taskId, true); // 标记为运行中
            try {
                Object crawlerData = crawlerService.executeCrawler(task.getCrawlerName());
                // 将爬虫数据入库
                int savedCount = crawlerDataService.saveData(task.getCrawlerName(), crawlerData);

                log.info("定时任务[{}]执行完成，爬虫[{}]数据入库{}条",
                        task.getTaskName(), task.getCrawlerName(), savedCount);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            // 可在此处记录日志
        } finally {
            crawlerTaskMapper.updateRunning(taskId, false); // 释放运行标记
        }
    }
}